package com.aaron.kjviewutils.flight;

import android.os.Bundle;
import android.support.v7.widget.CardView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.aaron.kjviewutils.BaseActivity;
import com.aaron.kjviewutils.R;
import com.aaron.kjviewutils.eventBus.BundleEventMsg;
import com.aaron.kjviewutils.retrofit.RetrofitUtil;
import com.bumptech.glide.Glide;
import com.github.ybq.android.spinkit.Style;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 作者：Aaron on 2017/2/23 14:29
 * 邮箱：kaijin.fang@edianniu.com
 */
public class FlightDetailActivity extends BaseActivity {

    @Bind(R.id.flightDetailToolbar)
    Toolbar flightDetailToolbar;
    @Bind(R.id.leftBarIcon)
    ImageView leftBarIcon;
    @Bind(R.id.titleBg)
    ImageView titleBg;
    @Bind(R.id.flightDetailL)
    LinearLayout flightDetailL;

    private FlightService flightService;
    private Call<FlightLineBean> callLineDetail;
    private FlightLineBean.FlightLineInner flightLine;

    @OnClick(R.id.leftBarIcon)
    void leftBarIconClick()
    {
        closeSelf(FlightDetailActivity.this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true, priority = 100)
    public void onEventSticky(BundleEventMsg msg)
    {
        switch (msg.getType())
        {
            case BUNDLE_FLIGHT_DETAIL_STICKY:
            {
                Bundle bundle = msg.getBundle();
                flightLine = (FlightLineBean.FlightLineInner) bundle.getSerializable("flightLine");
                if(null!=eventBus)
                {
                    eventBus.removeStickyEvent(msg);
                }
            }
            break;
            default:
                break;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN, priority = 80)
    public void onEvent(BundleEventMsg msg)
    {
        switch (msg.getType())
        {
            case BUNDLE_FLIGHTDETAIL_UI:
            {
                Bundle bundle = msg.getBundle();
                FlightLineBean flightLine = (FlightLineBean) bundle.getSerializable("flightLine");
                if(null!=flightLine)
                {
                    List<FlightLineBean.FlightLineInner> flightLineInners = flightLine.result;
                    if(null!=flightLineInners&&!flightLineInners.isEmpty())
                    {
                        //动态加载数据
                        flightDetailL.removeAllViews();
                        for(FlightLineBean.FlightLineInner flightLineInner:flightLineInners)
                        {
                            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup
                                    .LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                            CardView flightCardL = (CardView) LayoutInflater.from(FlightDetailActivity.this).inflate(R.layout.item_flightline, null);
                            TextView flightNo = (TextView) flightCardL.findViewById(R.id.flightNo);
                            TextView airLines = (TextView) flightCardL.findViewById(R.id.airLines);
                            TextView from = (TextView) flightCardL.findViewById(R.id.from);
                            TextView to = (TextView) flightCardL.findViewById(R.id.to);
                            TextView planTime = (TextView) flightCardL.findViewById(R.id.planTime);
                            TextView planArriveTime = (TextView) flightCardL.findViewById(R.id.planArriveTime);
                            TextView flightTime = (TextView) flightCardL.findViewById(R.id.flightTime);
                            TextView week = (TextView) flightCardL.findViewById(R.id.week);
                            flightNo.setText("航班号:"+flightLineInner.flightNo);
                            flightTime.setText("飞行时间:" + flightLineInner.flightTime);
                            from.setText("出发机场:" + flightLineInner.from);
                            to.setText("到达机场:" + flightLineInner.to);
                            planTime.setText("起飞时间:" + flightLineInner.planTime);
                            planArriveTime.setText("到达时间:" + flightLineInner.planArriveTime);
                            airLines.setText("航空公司:" + flightLineInner.airLines);
                            week.setText("航班周期:" + flightLineInner.week);
                            flightCardL.setLayoutParams(lp);
                            flightDetailL.addView(flightCardL);
                        }
                    }
                }
            }
            break;
            default:
                break;
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setContentView(R.layout.layout_flight_detail);
        ButterKnife.bind(this);
        initTitle();
        mHandler.postDelayed(runnableLoad, 1000);
    }

    Runnable runnableLoad = new Runnable() {
        @Override
        public void run() {
            if(null!=flightLine)
            {
                if(null!=progress)
                {
                    progress.showProgress(Style.WAVE);
                    progress.showAtLocation(flightDetailToolbar, Gravity.CENTER, 0, 0);
                }
                //获取航班信息
                if(null==retrofit)
                {
                    retrofit = RetrofitUtil.obtainRetrofit();
                }
                flightService = retrofit.create(FlightService.class);
                callLineDetail = flightService.obtainFlightByNo(flightLine.flightNo);
                callLineDetail.enqueue(new Callback<FlightLineBean>() {
                    @Override
                    public void onResponse(Call<FlightLineBean> call, Response<FlightLineBean> response) {
                        callLineDetail.cancel();
                        if (null != progress) {
                            progress.dismissView();
                        }
                        FlightLineBean flightLine = response.body();
                        if ("200".equals(flightLine.retCode)) {
                            //获取信息,绘制界面
                            Bundle bundle = new Bundle();
                            bundle.putSerializable("flightLine", flightLine);
                            eventBus.post(new BundleEventMsg(BundleEventMsg.EventBusType.BUNDLE_FLIGHTDETAIL_UI, bundle));
                        } else {
                            showMsg(flightLine.msg);
                        }
                    }

                    @Override
                    public void onFailure(Call<FlightLineBean> call, Throwable t) {
                        callLineDetail.cancel();
                        if (null != progress) {
                            progress.dismissView();
                        }
                        showMsg("获取航班信息失败");
                    }
                });
            }

        }
    };

    private void initTitle()
    {
        flightDetailToolbar.setTitle((null == flightLine) ? "未知航班" : (TextUtils.isEmpty(flightLine.flightNo)) ? "未知航班" : "航班号"+flightLine.flightNo);
        setSupportActionBar(flightDetailToolbar);
        loadBackground(leftBarIcon, resources.getDrawable(R.mipmap.back));
        flightDetailToolbar.setNavigationIcon(null);
        Glide.with(FlightDetailActivity.this).load("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1488437372&di=4add34de7d5259d4a83ae79f4801e6be&imgtype=jpg&er=1&src=http%3A%2F%2Ffinance.hebnews.cn%2Fnews%2Fattachement%2Fjpg%2Fsite2%2F20140310%2F7845c40ee8c5148758f307.jpg").animate(android.R.anim.slide_in_left).centerCrop().into(titleBg);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN)
        {
            //关闭
            closeSelf(FlightDetailActivity.this);
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(null!=mHandler)
        {
            mHandler.removeCallbacks(runnableLoad);
        }
        if(null!=callLineDetail)
        {
            callLineDetail.cancel();
        }
        ButterKnife.unbind(this);
    }
}
